/**
 * Class: Ticker
 *
 * Purpose: 
 *
 * Created: Feb 18, 2010 @ 3:28:58 PM
 * @author Ken Scott
 */
package org.openfantasia.time;

import org.openfantasia.util.listener.DoubleScalar;
import org.openfantasia.util.listener.Event;
import org.openfantasia.util.listener.Listener;

public abstract class Ticker implements Listener {

	public static final String TIME = "time";

	protected Timebase timebase;

	protected long periodNS;

	protected long nextTickNS;


	public Ticker(long periodNS) {
		this.periodNS = periodNS;
	}


	public Ticker(double periodS) {
		this.periodNS = (long) (periodS * 1e9);
	}


	public Timebase getTimebase() {
		return timebase;
	}


	public void setTimebase(Timebase timebase) {
		this.timebase = timebase;
	}


	public long getPeriodNS() {
		return periodNS;
	}


	public void setPeriodNS(long periodNS) {
		this.periodNS = periodNS;
	}


	public double getPeriod() {
		return (double) periodNS / 1e9;
	}


	public void tick(final long timeNS) {
		if (timeNS >= nextTickNS) {
			nextTickNS += periodNS;

			double time = (double) timeNS / 1e9;

			final DoubleScalar scalar = new DoubleScalar(time);
			scalar.setChannel(TIME);
			scalar.setTime(time);

			receive(scalar);
		}
	}


	public abstract void receive(Event event);
}
